﻿<link href="~/Plugin/plupload/css/jquery.plupload.queue.css" rel="stylesheet" />
<link href="~/Plugin/jqueryui/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Plugin/jqueryui/jquery-ui.min.js"></script>
<script src="~/Plugin/plupload/scripts/plupload.full.min.js"></script>
<script src="~/Plugin/plupload/scripts/jquery.plupload.queue.min.js"></script>

<body>
    <input id="current" type="hidden" />
    <div class="nd-btns">
        <a href="javascript:;" onclick="openInsertWindow()">新建文件夹</a> |
        <a href="javascript:;" onclick="openEditWindow()">重命名</a> |
        <a href="javascript:;" onclick="deleteFile()">删除</a> |
        <a href="javascript:;" id="pup-btn">文件上传</a> |
        <a href="javascript:;" onclick="downloadFile()">文件下载</a> |
        <a href="javascript:;" onclick="previewFile()">预览</a> |
        <a href="javascript:;" onclick="moveFile()">移动</a>
    </div>
    <input id="pathload" type="hidden" />
    <div class="nd-crumbs">
        <a href="javascript:;">公共网盘</a>
        <span> >  <a href="#">根目录</a></span>
        <span> >  <a href="#">二级目录</a></span>
    </div>
    <div class="nd-files"></div>
    <div id="pup-main" hidden></div>
</body>

<script>
    $(function () {
        refresh();
        initUploader();

        // 多选控件
        $(".nd-files").selectable({
            filter: ".nd-file",
            cancel: '.ui-selected',
        });
    })

    /*
     * 控制 selectable 控件不屏蔽单击事件
     * 同样达到单击可以选择的效果
    */
    $('.ui-selected').on('click', function () {
        $(this)
            .removeClass('ui-selected')
            .parents('.ui-selectable')
            .trigger('selectablestop');
    });

    /**
     * 面包屑点击事件
     */
    $(".nd-crumbs").on("click", "a", function (e) {
        var id = $(this).attr("id");
        var cur = $("#current").val();
        if (id != cur) {
            refresh(id);
        }
    })

    /**
     * 文件夹&文件双击时间
     * 文件双击是预览
     * 文件夹双击是打开
     */
    $(".nd-files").on("dblclick", ".nd-file", function (e) {
        var id = $(this).attr("id");
        var isFolder = $(this).attr("is-folder");
        if (isFolder === "true") {
            refresh(id);
        }
    })

    /**
     *  添加一个文件
     */
    function appendFile(file) {
        var content = "<div id='" + file.Id + "' title='" + file.Name + "' class='nd-file' is-folder='" + file.IsFolder + "'>" +
                            "<div class='nd-file-icon'>" +
                                "<img src='" + file.Icon + "' />" +
                            "</div>" +
                            "<div class='nd-file-name'>" +
                                "<span>" + file.AbbreviationName + "</span>" +
                            "</div>" +
                        "</div>";
        $(".nd-files").append(content);
    }

    /**
     * 打开新增文件夹窗口
     */
    function openInsertWindow() {
        var currentId = $("#currentId").val();
        if (currentId == undefined) {
            currentId = 0;
        }
        openWindow('新建文件夹', '/CloudStorage/Update', { fileId: 0, currentId: currentId });
    }

    /**
     * 打开文件重命名窗口
     */
    function openEditWindow() {
        var file = $(".ui-selected");
        if (file.length < 1) {
            alert('未选择文件!');
        }
        else if (file.length > 1) {
            alert('一次只能重命名一个文件!');
        }
        else {
            var Id = file.attr("id");
            openWindow('重命名', '/CloudStorage/Update', { fileId: Id, currentId: 0 });
        }
    }

    /**
     * 删除文件
     * 如果删除多个文件的情况下
     * 如果当中有不符合删除规则的文件
     * 则不执行删除动作
     */
    function deleteFile() {
        var file = $(".ui-selected");
        if (file.length <= 0) {
            alert("请至少选择一个文件进行删除!");
        }
        else {
            kendo.confirm("文件删除无法恢复! 你确定要删除这" + file.length + "个文件吗?", "文件删除").then(function () {
                var fileId = new Array();
                file.each(function (index, element) {
                    fileId.push(element.id);
                })

                $.post({
                    url: "/CloudStorage/Delete",
                    dataType: 'json',
                    data: { FileId: fileId },
                    success: function (response) {
                        if (response.IsSuccess) {
                            file.remove();
                            openNotification(response.Message, "success");
                        }
                        else {
                            openNotification(response.Message, "error");
                        }
                    },
                    error: ajaxError
                })
            })
        }
    }

    /**
     * 下载文件
     * 如果只有单个文件, 则直接下载
     * 如果超过一个文件, 则打包下载
     * 文件夹不能下载, 并中断其他文件下载
     */
    function downloadFile() {
        var file = $(".ui-selected");
        if (file.length <= 0) {
            alert('请至少选择一个文件进行下载!');
        }
        else {
            var fileId = new Array();
            file.each(function (index, element) {
                fileId.push(element.id);
            })
            $.post({
                url: "/CloudStorage/PrepareDownload",
                dataType: 'json',
                data: { FileId: fileId },
                success: function (response) {
                    if (response.IsSuccess) {
                        location.href = "/CloudStorage/Download?path=" + response.Data;
                        //openNotification(response.Message, "success");
                    }
                    else {
                        openNotification(response.Message, "error");
                    }
                },
                error: ajaxError
            })
        }
    }

    /**
     * 刷新当前界面
     * @@param int fileId 文件或文件夹Id
     */
    function refresh(fileId) {
        loadCrumbs(fileId);
        loadFiles(fileId);
        $("#current").val(fileId);
    }

    /**
     * 刷新当前面包屑
     * @@param int fileId 文件或文件夹Id
     */
    function loadCrumbs(fileId) {
        var pathload = "\\";
        var content = "<a href='javascript:;'>公共网盘</a>";
        $(".nd-crumbs").html(content);
        $.ajax({
            url: '/CloudStorage/ReadCrumbs',
            dataType: 'json', type: 'post',
            data: { fileId: fileId },
            success: function (response) {
                for (var i in response) {
                    pathload += response[i].Title + "\\";
                    content += "<span> >  <a id='" + response[i].Href + "'>" + response[i].Title + "</a></span>";
                }
                $("#pathload").val(pathload);
                $(".nd-crumbs").html(content);
            },
            error: ajaxError,
        })
    }

    /**
     * 刷新当前目录
     * @@param int fileId 文件或文件夹Id
     */
    function loadFiles(fileId) {
        $(".nd-files").html("loading.....");
        $.ajax({
            url: '/CloudStorage/Read',
            dataType: 'json', type: 'post',
            data: { fileId: fileId },
            success: function (response) {
                var content = "";
                for (var i in response) {
                    content += "<div id='" + response[i].Id + "' title='" + response[i].Name + "' class='nd-file' is-folder='" + response[i].IsFolder + "'>" +
                                    "<div class='nd-file-icon'>" +
                                        "<img src='" + response[i].Icon + "' />" +
                                    "</div>" +
                                    "<div class='nd-file-name'>" +
                                        "<span>" + response[i].AbbreviationName + "</span>" +
                                    "</div>" +
                                "</div>";
                }
                $(".nd-files").html(content);
            },
            error: ajaxError,
        })
    }
    
    /*
    * 将标签实例化为一个文件上传器
    */
    function initUploader() {
        var _btn = "pup-btn";
        var obj = $("#pup-main");
        obj.pluploadQueue({
            runtimes: 'html5',
            browse_button: _btn,
            url: "/File/Uploader",
            unique_names: false,
            multipart_params: {
                pathload: $("#pathload").val(),
            },
            multi_selection: true,
            chunk_size: "1mb",
            filters: {
                prevent_duplicates: false
            },
            // 最大重试次数
            max_retries: 0,
            init: {
                FilesAdded: function (uploader, files) {
                    uploader.settings.multipart_params.pathload = $("#pathload").val();
                    uploader.start();
                },
                FileUploaded: function (uploader, file, responseObject) {
                    // 获取响应对象
                    response = jQuery.parseJSON(responseObject.response);
                    //alert(response.IsSuccess)
                    //console.log(response.Data);
                    // 文件对象保存到数据库
                    if (response.IsSuccess) {
                        response.Data.ParentId = $("#current").val();
                        saveFileToDB(response.Data);
                    }
                    else {
                        openNotification(response.Message, "error");
                    }
                },
                UploadProgress: function (uploader, file) {

                },
                UploadComplete: function (uploader, files) {
                    $(".plupload_upload_status").hide();
                    $(".plupload_buttons").show();
                    // 图片传送完成 可以继续上传其他图片
                    uploader.disableBrowse(false);
                },
                Error: function (uploader, errObject) {
                },
            },
        });
    }

    /**
     * 将文件保存到数据库
     * @@param obj 文件实体
     */
    function saveFileToDB(obj) {
        //alert(obj.Id);
        $.ajax({
            url: '/CloudStorage/Update',
            dataType: 'json', type: 'post',
            data: { file: obj },
            success: function (response) {
                if (response.IsSuccess) {
                    openNotification(response.Message, "success");
                    appendFile(response.Data);
                }
                else {
                    openNotification(response.Message, "error");
                }
                //var currentId = $("#current").val();
                //refresh(currentId);
            },
            error: ajaxError
        });
    }
</script>